/**************************************************************
  > File Name: fileSize.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年02月11日 星期五 09时40分39秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>

#define NAMEBUFSIZE 1024

int isLoop(char *pathname)
{
	char *pos = NULL;
	pos = strrchr(pathname, '/');
	if (pos == NULL)
	{
		exit(1);
	}
	if (strcmp(pos+1, ".") == 0 || strcmp(pos+1, "..") == 0)
		return 1;
	return 0;
}

int func(char *pathname)
{
	int ret;
	int sum = 0;
	struct stat statbuf;

	ret = stat(pathname, &statbuf);
	if (ret < 0)
	{
		perror("stat()");
		exit(1);
	}

	if ((statbuf.st_mode & S_IFMT) != S_IFDIR)
	{
		return statbuf.st_size;	
	}
	
	DIR *dir;
	struct dirent *dirRet;
	char nameBuf[NAMEBUFSIZE] = {0};

	dir = opendir(pathname);
	if (dir == NULL)
	{
		perror("opendir()");
		exit(1);
	}

	while ((dirRet = readdir(dir)) != NULL)
	{
		sprintf(nameBuf, "%s/%s", pathname, dirRet->d_name);
		if (isLoop(nameBuf) == 0)
		{
			sum += func(nameBuf);
		}
		memset(nameBuf, 0, strlen(nameBuf));
	}
	closedir(dir);
	return sum;
}


int main(int argc, char **argv)
{
	if (argc < 2)
	{
		fprintf(stderr, "Usage:\n");
		exit(1);
	}
	int ret;

	ret = func(argv[1]);
	printf("%d\n",ret);

    exit(0);
}
